package com.feicheng.controller.shop.wx.app.client;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.feicheng.common.constant.Constant;
import com.feicheng.common.result.ResultInfo;
import com.feicheng.controller.BaseController;
import com.feicheng.persistence.entity.Client;
import com.feicheng.persistence.entity.StoreClient;
import com.feicheng.persistence.entity.WxServer;
import com.feicheng.persistence.service.IClientService;
import com.feicheng.persistence.service.IStoreClientService;
import com.feicheng.service.IFLoginService;
import com.feicheng.wxapi.app.WxApi;

import lombok.extern.slf4j.Slf4j;

@RestController("/wx/app/client/login")
@RequestMapping("/wx/app/client/login")
@Slf4j
public class LoginController extends BaseController {

    @Resource(name="client-login")
    Map<String, IFLoginService> loginService;
    
    @Autowired
    IStoreClientService storeClientService;
    
    @Autowired
    IClientService clientService;
    
    @Autowired
    WxApi wxApi;

    @GetMapping("/wx-code")
    public ResultInfo wxCodeLogin(String code, String appId, String phoneCode) {
        JSONObject param = new JSONObject();
        param.put(Constant.WX.PARAM.CODE, code);
        param.put("PHONE_CODE", phoneCode);
        param.put(Constant.WX.PARAM.APPID, appId);

        ResultInfo result = loginService.get(Constant.LOGIN_TYPE.WX_APP).login(param.toJSONString());
        if (Constant.RESULT.SUCCESS.equals(result.getString(Constant.RESULT.STATU))) {
            super.setToken(Constant.RESULT.CURRENT, result.getJSONObject(Constant.RESULT.DATA));
        }
        return result;
    }
    
    @GetMapping("/phone")
    public ResultInfo getPhoneNumber(String code) {
    	
    	JSONObject current = super.getCurrentToken().getToken().getJSONObject(Constant.RESULT.CURRENT);
    	StoreClient sc = current.getObject(Constant.ENTITY.STORE_CLIENT.TABLE, StoreClient.class);
    	WxServer wx = current.getObject(Constant.ENTITY.WX_SERVER.TABLE, WxServer.class);
    	String phone = wxApi.getPhoneNumber(sc.getStoreId(), sc.getOpenId(), wx.getAppId(), wx.getAccessKey(), code);
    	Client client = current.getObject(Constant.ENTITY.CLIENT.TABLE, Client.class);
    	client.setPhone(phone);
    	clientService.updateById(client);
    	
    	return ResultInfo.success(phone);
    }
    
    
}
